import asyncio
import aiofiles
import threading
import time

# 每个线程运行的协程逻辑
async def async_write_file(filename, content):
    async with aiofiles.open(filename, 'w', encoding='utf-8') as f:
        await f.write(content)
    print(f"[协程] 写入完成：{filename}")

# 每个线程启动一个 event loop 执行异步任务
def thread_worker(thread_id):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    content = f"这是线程 {thread_id} 的数据\n" * 1000000
    filename = f"async_thread_{thread_id}.txt"

    loop.run_until_complete(async_write_file(filename, content))
    loop.close()
    print(f"[线程] 线程 {thread_id} 执行完成")

if __name__ == "__main__":
    start = time.time()
    threads = []

    # 启动多个线程，每个线程内部异步写一个文件
    for i in range(5):
        t = threading.Thread(target=thread_worker, args=(i,))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

    print("所有线程完成，总耗时：", time.time() - start)
